﻿using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;

namespace BookSourceVerification.service.impl;

public class CheckSourceHttpServiceImpl : ICheckBookSourceService
{
    private const double Timeout = 1000;
    private static IHttpClientFactory? HttpClientFactory;

    public CheckSourceHttpServiceImpl()
    {
        HttpClientFactory =
            App.ServiceProvider?.GetService<IHttpClientFactory>() ?? throw new Exception("http 客户端创建失败");
    }

    public async Task<bool> Check(string url)
    {
        try
        {
            var httpClient = HttpClientFactory?.CreateClient() ?? throw new Exception("httpclient 创建失败！");
            httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout);
            using var httpResponseMessage = await httpClient.GetAsync(url);
            var httpStatusCode = (int)httpResponseMessage.StatusCode;
            Console.WriteLine(httpStatusCode);
            return httpStatusCode is >= 200 and < 400;
        }
        catch (Exception exception)
        {
            throw new Exception($"，url: {url}", exception);
        }
    }
}